package com.cskaoyan.mall.payment.controller.inner;

import com.alipay.api.response.AlipayTradeQueryResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.cskaoyan.mall.common.result.Result;
import com.cskaoyan.mall.pay.api.dto.PaymentInfoDTO;
import com.cskaoyan.mall.payment.constant.PaymentStatus;
import com.cskaoyan.mall.payment.converter.PaymentInfoConverter;
import com.cskaoyan.mall.payment.mapper.PaymentInfoMapper;
import com.cskaoyan.mall.payment.model.PaymentInfo;
import com.cskaoyan.mall.payment.pay.alipay.AlipayHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * @Author Pudding
 * @Date 2024/7/17 21:42
 */
@RestController
public class PayApiController {

    @Autowired
    PaymentInfoMapper paymentInfoMapper;
    @Autowired
    PaymentInfoConverter paymentInfoConverter;
    @Autowired
    AlipayHelper alipayHelper;

    /**
     * 根据外部订单号 查询支付记录
     */
    @GetMapping("/api/payment/inner/getPaymentInfoByOutTradeNo/{outTradeNo}")
    PaymentInfoDTO getPaymentInfoDTOByOutTradeNo(@PathVariable(value = "outTradeNo") String outTradeNo){

        LambdaQueryWrapper<PaymentInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(PaymentInfo::getOutTradeNo,outTradeNo);

        PaymentInfo paymentInfo = paymentInfoMapper.selectOne(lambdaQueryWrapper);

        PaymentInfoDTO paymentInfoDTO = paymentInfoConverter.convertPaymentInfoToDTO(paymentInfo);

        return paymentInfoDTO;
    }

    /**
     * 根据外部订单号 查询支付宝支付状态
     */
    @GetMapping("/api/payment/inner/getAlipayInfo/{outTradeNo}")
    Result<Map<String, String>> getAlipayInfo(@PathVariable(value = "outTradeNo") String outTradeNo){

        Map<String, String> map = alipayHelper.queryTradeStatus(outTradeNo);
        return Result.ok(map);
    }

    /**
     * 关闭支付宝支付记录
     */
    @GetMapping("/api/payment/inner/closeAlipay/{outTradeNo}")
    Result closeAlipay(@PathVariable(value = "outTradeNo") String outTradeNo){

        alipayHelper.closeTrade(outTradeNo);
        return Result.ok();
    }

    /**
     * 修改paymentInfo为已关闭
     */
    @GetMapping("/api/payment/inner/closePaymentInfo/{outTradeNo}")
    Result closePaymentInfo(@PathVariable(value = "outTradeNo") String outTradeNo){

        LambdaUpdateWrapper<PaymentInfo> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(PaymentInfo::getOutTradeNo,outTradeNo)
                .set(PaymentInfo::getPaymentStatus, PaymentStatus.CLOSED.name());

        paymentInfoMapper.update(null,lambdaUpdateWrapper);

        return Result.ok();
    }
}
